import Vue from 'vue'
import server from '@/utils/request'
import router from './router.js'
import store from './store/'
// request 拦截器
server.interceptors.request.use(function(config) {
  if (store.getters.isLogin && store.getters.token !== undefined) {
    config.headers['Authorization'] = 'Bearer ' + store.getters.token // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, function(error) {
  return Promise.reject(error)
})

// response 拦截器
server.interceptors.response.use(function (response) {
  return response
}, function (error) {
  if (error.response.status !== 200) {
    switch (error.response.status) {
      case 401:
        store.commit('logout')
        Vue.prototype.$toasted.error('登录超时，请重新登录！', { icon: 'error' })
        router.push({ name: 'Login' })
        break
      case 403:
        store.commit('logout')
        Vue.prototype.$toasted.error('未登录！请先登录！', { icon: 'error' })
        router.push({ name: 'Login' })
        break
      case 404:
      default:
        // Vue.prototype.$toasted.error(error.response.data || error.response.status, { icon: 'error' })
        Vue.prototype.$toasted.error(error.response.data.message || error.response.status, { icon: 'error' })
        break
    }
  }
  return Promise.reject(error)
})
